<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="referrer" content="no-referrer">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>网络收藏夹|登录</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="layui/css/layui.css">
    <style>


        .layui-breadcrumb a {
            color: #333!important;
        }

        .bg{
            position: fixed;
            top: 100px;
            left: 0;
            right: 0;
            bottom: 100px;
            background: #009688;
        }

        .loginTitle{
            margin-top: 20px;
            margin-left: 15px;
            background: #fff;
            font-weight: bold;
            font-size: 18px;
        }

        .loginDiv{
            z-index: 999;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 400px;
            background: white;
            padding: 10px;
            border-radius: 4px;
            box-shadow: 0 5px 15px -5px rgba(0,0,0,.5);
        }

        .loginFooter{
            position: fixed;
            bottom: 0;
            width: 100%;
            text-align: center;
            height: 44px;
            line-height: 44px;
        }

        #qrcode {
            padding: 15px;
            border: 1px solid #e5e5e5;
            width: 180px;
            height: 180px;
            margin: 15px auto;
        }

        #refreshCode {
            margin-left: 10px;
            cursor: pointer;
        }

        #refreshCode:hover {
            color: #5fb878;
        }

        .pwdValid{
            display: none;
            align-items: baseline;
            margin-top: 10px;
            font-size: 12px;
            color: #666;
        }

        .pwdValid span{
            display: inline-block;
            height: 5px;
            width: 40px;
            background: #e2e2e2;
            margin-right: 5px;
        }

        .pwdValid span.active{
            background: #5fb878;
        }

        .pwdValid em {
            font-style: normal;
        }

        .pwdValid em.prev{
            margin-right: 10px;
        }

        .pwdValid em.name{
            margin-left: 10px;
        }

        img.verifyCode{
            position: absolute;
            right: 6px;
            top: 2px;
            height: 34px;
            cursor: pointer;
        }

    </style>
</head>
<body>
<blockquote class="layui-elem-quote loginTitle">网络收藏夹</blockquote>
<div class="bg" id="particles-js"></div>
<div class="layui-tab layui-tab-brief loginDiv">
    <ul class="layui-tab-title">
        <li class="layui-this">登录</li>
        <li>注册</li>
        <li>忘记密码</li>
    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
            <!-- 登录表单 -->
            <form class="layui-form" action="" id="loginForm">
                <input type="hidden" name="sid" id="sid">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名"
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">验证码</label>
                    <div class="layui-input-block">
                        <input type="text" name="code" id="code" required lay-verify="required" placeholder="请输入验证码"
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <input type="checkbox" name="remember" value="1" title="两周内自动登录" lay-skin="primary">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="login">登录</button>
                    </div>
                </div>
            </form>
            <div id="qrcodeDiv" style="display:none;">
                <div style="text-align: center;">请使用手机扫一扫登录
                    <span id="refreshCode">刷新
                        <i class="layui-icon layui-icon-refresh-3" style="font-size: 14px;"></i>
                    </span>
                </div>
                <div id="qrcode"></div>
            </div>
            <form class="layui-form" action="" style="display:none;" id="emailLogin">
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱账号</label>
                    <div class="layui-input-block">
                        <input type="email" name="email" id="login-email" required lay-verify="required|email"
                               placeholder="输入您的邮箱" autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">验证码</label>
                    <div class="layui-input-inline" style="width:170px;">
                        <input type="text" name="code" required lay-verify="required" placeholder="请输入验证码"
                               autocomplete="off" class="layui-input">
                    </div>
                    <input type="button" class="layui-btn layui-btn-sm" style="margin-top:4px;width: 90px;"
                           onclick="sendLoginEmailCode(this)" value="获取验证码">
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="emailLogin">登录</button>
                    </div>
                </div>
            </form>
            <div style="padding-left: 14px;padding-top: 10px;">
                <span class="layui-breadcrumb" lay-separator="|">
                  <a href="javascript:;" onclick="emailLogin(this)">邮箱登录</a>
                  <a href="javascript:;" onclick="qrcodeLogin(this)">扫码登录</a>
                </span>
                <span class="layui-breadcrumb" style="display:none;">
                  <a href="javascript:;" onclick="changeLogin(this)">
                      <i class="layui-icon layui-icon-left" style="font-size: 14px;margin-right: 2px;"></i>切换其他登录方式
                  </a>
                </span>
            </div>
        </div>
        <div class="layui-tab-item">
            <!-- 注册表单 -->
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required|username"
                               placeholder="输入6~18个字符，字母、数字、下划线"
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">设置密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" id="password" required lay-verify="required|password"
                               placeholder="输入6~16个字符，区分大小写"
                               autocomplete="off"
                               class="layui-input">
                        <div id="pwdValid" class="pwdValid">
                            <em class="prev">密码强度：</em>
                            <span></span>
                            <span></span>
                            <span></span>
                            <em class="name">低</em>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱</label>
                    <div class="layui-input-block">
                        <input type="email" name="email" id="register-email" required
                               lay-verify="required|email|exitEmail"
                               placeholder="输入您的邮箱" autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">验证码</label>
                    <div class="layui-input-inline" style="width:170px;">
                        <input type="text" name="code" required lay-verify="required" placeholder="请输入验证码"
                               autocomplete="off" class="layui-input">
                    </div>
                    <input type="button" class="layui-btn layui-btn-sm" style="margin-top:4px;width: 90px;"
                           onclick="sendEmailCode(this)" value="获取验证码">
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="register">注册</button>
                    </div>
                </div>
            </form>
        </div>
        <div class="layui-tab-item">
            <!-- 忘记密码 -->
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">登陆账号</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required"
                               placeholder="请输入登陆账号"
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱</label>
                    <div class="layui-input-block">
                        <input type="email" name="email" id="forgot-email" required lay-verify="required|email"
                               placeholder="请输入邮箱"
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">验证码</label>
                    <div class="layui-input-inline" style="width:170px;">
                        <input type="text" name="code" required lay-verify="required" placeholder="请输入验证码"
                               autocomplete="off" class="layui-input">
                    </div>
                    <input type="button" class="layui-btn layui-btn-sm" style="margin-top:4px;width: 90px;"
                           onclick="sendForgotEmailCode(this)" value="获取验证码">
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="forgotPwd">提交</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="loginFooter">
    © 2020 网络收藏夹 || 网络收藏夹版权所有
</div>
<script src="layui/jquery-3.1.1.min.js"></script>
<script src="layui/layui.js"></script>
<script src="layui/particles.min.js"></script>
<script src="layui/qrcode.min.js"></script>
<script src="layui/md5.min.js"></script>
<script>
    //注意：选项卡 依赖 element 模块，否则无法进行功能性操作
    layui.use(['element', 'form', 'layer'], function () {
        var element = layui.element;
        var form = layui.form;
        var layer = layui.layer;

        var socketPort = 8888;

        /* particlesJS.load(@dom-id, @path-json, @callback (optional)); */
        particlesJS.load('particles-js', 'layui/particles.json');

        var verifyCodeTimer;
        window.loadVerifyCode = function(){
            $.ajax({
                type: "GET",
                url: 'login/captcha',
                dataType: 'json',
                success: function (result) {
                    if (result.code == 0) {
                        $("#sid").val(result.data.key);
                        $("#code").next().remove();
                        $("#code").after('<img class="verifyCode" src="' + result.data.image + '" alt="验证码" onclick="loadVerifyCode()">');
                        clearInterval(verifyCodeTimer);
                        verifyCodeTimer = setInterval(loadVerifyCode, 60000);
                    }
                }
            });
        };

        loadVerifyCode();

        // 刷新二维码
        $("#refreshCode").click(function(){
            // 初始化二维码
            var sid = uuid();
            initQrCode(sid);
            initWebSocket(sid);
        });

        window.uuid = function() {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        };

        var qrcode;
        window.initQrCode = function(sid){
            var url = window.location.href;
            var path = url.substring(0,url.lastIndexOf("/"));
            var content = path + "/qrLogin.html?sid=" + sid;
            if(!qrcode){
                qrcode = new QRCode("qrcode", {
                    text: content,
                    width: 180,
                    height: 180,
                    colorDark : "#000000",
                    colorLight : "#ffffff",
                    correctLevel : QRCode.CorrectLevel.H
                });
            }else{
                qrcode.clear();
                qrcode.makeCode(content);
            }
        };

        // 邮箱登录
        window.emailLogin = function(obj){
            $("#loginForm").hide();
            $("#qrcodeDiv").hide();
            $("#emailLogin").show();
            $(obj).parent().hide().next().show();
        };

        // 切换登录方式
        window.changeLogin = function(obj){
            $("#emailLogin").hide();
            $("#qrcodeDiv").hide();
            $("#loginForm").show();
            $(obj).parent().hide().prev().show();
        };

        // 扫码登录
        window.qrcodeLogin = function(obj){
            $("#loginForm").hide();
            $("#emailLogin").hide();
            $("#qrcodeDiv").show();
            $(obj).parent().hide().next().show();
            // 初始化二维码
            var sid = uuid();
            initQrCode(sid);
            initWebSocket(sid);
        };

        var socket;
        window.initWebSocket = function(sid){
           if(typeof(WebSocket) == "undefined") {
               console.log("您的浏览器不支持WebSocket");
           }else{
               console.log("您的浏览器支持WebSocket");
               if(socket){ socket.close(); }
               socket = new WebSocket("ws://" + window.location.host.split(':')[0] + ":" + socketPort + "/websocket?sid=" + sid);
               //打开事件
               socket.onopen = function() {
                   console.log("Socket 已打开");
               };
               //获得消息事件
               socket.onmessage = function(msg) {
                   var result = JSON.parse(msg.data);
                   if(result.code == 0){
                       localStorage.setItem("login_user_token", result.data);
                       window.location.href = "index.html";
                   }
               };
               //关闭事件
               socket.onclose = function() {
                   console.log("Socket已关闭");
               };
               //发生了错误事件
               socket.onerror = function() {
                   alert("Socket发生了错误");
               }
           }
        };

        //监听提交
        form.on('submit(emailLogin)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "login/emailLogin",
                data: data.field,
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        localStorage.setItem("login_user_token", result.data);
                        window.location.href = "index.html";
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                },
                error: function () {
                    layer.closeAll('loading');
                    layer.msg("服务器异常", {icon: 2});
                }
            });
            return false;
        });

        //监听提交
        form.on('submit(login)', function (data) {
            layer.load();
            // md5加密
            data.field.password = md5(data.field.password);
            $.ajax({
                type: "POST",
                url: "login?remember=" + data.field.remember,
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        localStorage.setItem("login_user_token", result.data);
                        window.location.href = "index.html";
                    } else {
                        layer.msg(result.msg, {icon: 5});
                        loadVerifyCode();
                    }
                },
                error: function () {
                    layer.closeAll('loading');
                    layer.msg("服务器异常", {icon: 2});
                }
            });
            return false;
        });

        form.on('submit(forgotPwd)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "login/forgot",
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        layer.msg("新密码已发送至您的邮箱...", {icon: 6});
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                },
                error: function () {
                    layer.closeAll('loading');
                    layer.msg("服务器异常", {icon: 2});
                }
            });
            return false;
        });

        form.on('submit(register)', function (data) {
            layer.load();
            // md5加密
            data.field.password = md5(data.field.password);
            $.ajax({
                type: "POST",
                url: "register",
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        localStorage.setItem("login_user_token", result.data);
                        window.location.href = "index.html";
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                },
                 error: function () {
                    layer.closeAll('loading');
                    layer.msg("服务器异常", {icon: 2});
                }
            });
            return false;
        });

        form.verify({
            username: function (value, item) {
                if(value.length<6||value.length>18||!/^[0-9a-zA-Z_]{1,}$/.test(value)){
                    return '输入6~18个字符，字母、数字、下划线';
                }
                var msg;
                $.ajax({
                    type: "GET",
                    url: 'register/' + value,
                    async: false,
                    dataType: 'json',
                    success: function (result) {
                        if (result.code != 0) {
                            msg = "用户已注册";
                        }
                    }
                });
                return msg;
            },
            exitEmail: function (value, item) {
                var msg;
                $.ajax({
                    type: "GET",
                    url: 'register/email/' + value,
                    async: false,
                    dataType: 'json',
                    success: function (result) {
                        if (result.code != 0) {
                            msg = "邮箱已被使用";
                        }
                    }
                });
                return msg;
            },
            password: function (value, item) {
                if(value.length<6||value.length>16){
                    return '输入6~16个字符，区分大小写';
                }
            }
        });

        // 验证强度
        $("#password").keyup(function(){
             $("#pwdValid").css("display","flex");
             var val = $(this).val();
             var lvTxt = ['', '低', '中', '高'];
             var lv = 0;
             if (val.match(/[a-z]/g)) { lv++; } //验证是否包含字母
             if (val.match(/[0-9]/g)) { lv++; } // 验证是否包含数字
             if (val.match(/(.[^a-z0-9])/g)) { lv++; } //验证是否包含字母，数字，字符
             if (val.length < 6) { lv = 0; } //如果密码长度小于6位，提示消息为空
             if (lv > 3) { lv = 3; }

             $("#pwdValid").find("span").each(function(index){
                if(index < lv) {
                    $(this).addClass("active");
                }else{
                    $(this).removeClass("active");
                }
             });
             $("#pwdValid").find(".name").text(lvTxt[lv]);
        });

        // 发送验证码
        window.sendEmailCode = function (obj) {
            var email = $("#register-email").val();
            var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if(email.match(reg)){
                obj.setAttribute("disabled", true);
                obj.value="重新发送(60)";
                // 倒计时
                var countdown = 59;
                var interval = setInterval(function() {
                    if (countdown == 0) {
                        obj.removeAttribute("disabled");
                        obj.value="获取验证码";
                        countdown = 59;
                        clearInterval(interval);
                    } else {
                        obj.setAttribute("disabled", true);
                        obj.value="重新发送(" + countdown + ")";
                        countdown--;
                    }
                }, 1000);
                // 请求后台
                $.ajax({
                    type: "GET",
                    url: "register/email/code",
                    data: {"email": email}
                });
            }else{
                $("#register-email").focus().addClass("layui-form-danger");
                 layer.msg('邮箱格式不正确', {icon: 5, anim: 6});
            }
        };
        
        // 发送验证码
        window.sendLoginEmailCode = function (obj) {
            var email = $("#login-email").val();
            var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if(email.match(reg)){
                obj.setAttribute("disabled", true);
                obj.value="重新发送(60)";
                // 倒计时
                var countdown = 59;
                var interval = setInterval(function() {
                    if (countdown == 0) {
                        obj.removeAttribute("disabled");
                        obj.value="获取验证码";
                        countdown = 59;
                        clearInterval(interval);
                    } else {
                        obj.setAttribute("disabled", true);
                        obj.value="重新发送(" + countdown + ")";
                        countdown--;
                    }
                }, 1000);
                // 请求后台
                $.ajax({
                    type: "GET",
                    url: "login/email/code",
                    data: {"email": email}
                });
            }else{
                $("#login-email").focus().addClass("layui-form-danger");
                 layer.msg('邮箱格式不正确', {icon: 5, anim: 6});
            }
        };

        window.sendForgotEmailCode = function (obj) {
            var email = $("#forgot-email").val();
            var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if(email.match(reg)){
                obj.setAttribute("disabled", true);
                obj.value="重新发送(60)";
                // 倒计时
                var countdown = 59;
                var interval = setInterval(function() {
                    if (countdown == 0) {
                        obj.removeAttribute("disabled");
                        obj.value="获取验证码";
                        countdown = 59;
                        clearInterval(interval);
                    } else {
                        obj.setAttribute("disabled", true);
                        obj.value="重新发送(" + countdown + ")";
                        countdown--;
                    }
                }, 1000);
                // 请求后台
                $.ajax({
                    type: "GET",
                    url: "login/forgot/code",
                    data: {"email": email}
                });
            }else{
                $("#forgot-email").focus().addClass("layui-form-danger");
                 layer.msg('邮箱格式不正确', {icon: 5, anim: 6});
            }
        };
    });

</script>
</body>
</html>